/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.base.users;

import java.util.List;
import org.urchr.web.db.DBSession;
import org.webos.java.base.SystemManager;
import org.webos.java.base.db.users.DBUser;
import org.webos.java.base.utils.MD5;
import org.webos.java.root.RandomGUID;

/**
 *
 * @author Kostya
 */
public class DBUserProvider implements UserProvider{

    public UserProfile checkUser(String userName, String password) {
        DBSession dbs = new DBSession();
        try {
            List<DBUser> result = dbs.createQuery("from DBUser where login=:login").
                    setString("login", userName.toLowerCase()).list();
            String md5 = MD5.makeHash(password);
            if(result.size()==0){
                //Add new user
                dbs.begin();
                DBUser user = new DBUser();
                user.setCode(new RandomGUID().toString());
                user.setLogin(userName.toLowerCase());
                user.setPassword(md5);
                user.setTimeZone(SystemManager.getProperty("default_time_zone", "Asia/Tokyo"));
                dbs.save(user);
                dbs.commit();
                UserProfile profile = new UserProfile(user.getCode());
                profile.setTimeZone(user.getTimeZone());
                profile.setFullName(userName);
                return profile;
            }
            if(md5.equals(result.get(0).getPassword())){
                UserProfile profile = new UserProfile(result.get(0).getCode());
                profile.setTimeZone(result.get(0).getTimeZone());
                profile.setFullName(userName);
                return profile;
            }
        } catch (Exception e) {
            dbs.rollback();
            e.printStackTrace();
        }finally{
            dbs.close();
        }
        return null;
    }

}
